import json
from flask_restful import Resource, current_app
from flask import request
from extensions import rest_api

from ...tasks.tasktest import stock_regist_task
from ...constants import (CELERY_EXCHANGE_TASKTEST, CELERY_ROUTING_KEY_TASKTEST,)
from jsonschema import validate
from .fields import regist_json_schema


__all__ = ['StockRegistApi', 'SaleStockSyncApi']


class StockRegistApi(Resource):
    """订单登记注册/取消登记API"

        ~优化需求(2016-10-09)~

            取消登记的时候，也不要检查实物库存了。 只判断有没有登记记录即可；
            如果有登记记录，则取消登记；
            如果已经取消登记了，直接返回成功；
            如果没有登记记录，再返回没有登记记录的提示

    """

    def post(self):
        try:
            regist_args = json.loads(request.data.decode())
            validate(regist_args, regist_json_schema)
        except Exception as e:
            return {'code': 400, 'msg': "{}".format(e)}
        current_app.logger.info("StockRegistApi receives regist_args: {}".format(regist_args))
        for order in regist_args:
            if order['business_type'] not in ('25', 25):
                return {'code': 400, 'msg': '{} 登记业务类型必须是25'.format(order['order_id'])}

        # stock_regist_task.apply_async(args=[regist_args],
        #                               queue=CELERY_EXCHANGE_REGIST,
        #                               routing_key=CELERY_ROUTING_KEY_REGIST)

        return {'code': 0, 'msg': 'successed', 'data': []}, 200


class SaleStockSyncApi(Resource):
    """
        销售库存同步
    """

    def post(self):
        # sync_sale_stock.apply_async(args=[],
        #                             queue=CELERY_EXCHANGE_SYNC_TO_B2C,
        #                             routing_key=CELERY_ROUTING_KEY_SYNC_TO_B2C)
        return 'SaleStockSyncApi', 200


rest_api.add_resource(StockRegistApi, '/stock/regist/')
rest_api.add_resource(SaleStockSyncApi, '/stock/sale_sync/')
